package com.frxuexi.myroom.paging

import androidx.paging.DataSource
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.room.Leave
import com.frxuexi.myroom.repository.LeaveRepository

class MyDataSource(leaveRepository: LeaveRepository,uname:String):PagingSource<Int,Leave>() {
    val leaveRepository=leaveRepository
    val uname=uname
    override fun getRefreshKey(state: PagingState<Int, Leave>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Leave> {
        return try {
            var currentPage=params.key?:1
            val list = leaveRepository.getMyLeaves(uname, currentPage, 10)
            val count = leaveRepository.getMyCount(uname)
            var sum = if(count%10==0) count/10 else count/10+1
            var nextPage=if(currentPage<sum){
                ++currentPage
            }else{
                null
            }

            LoadResult.Page(list,null,nextPage)
        }catch (e:Exception){
            return LoadResult.Error(e)
        }
    }
}